package com.wanbatv.wangwangba;

import android.app.Activity;
import android.graphics.Bitmap;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.Html;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


public class XiaobaikeActivity extends Activity {
    private ViewPager viewpager;
    ArrayList<View> viewContainter = new ArrayList<View>();
    private ViewpagerAdapter mAdapter=null;
    private TextView baike_yema_tv;
    private ImageView baike_jiantou_left;
    private ImageView baike_jiantou_right;
    private ImageView baike_image1;
    private Map<String,Bitmap> map=new HashMap<String,Bitmap>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_xiaobaike);
        viewpager=(ViewPager)findViewById(R.id.baike_viewpager);
        baike_yema_tv=(TextView)findViewById(R.id.baike_yema_tv);
        baike_jiantou_left=(ImageView)findViewById(R.id.baike_jiantou_left);
        baike_jiantou_right=(ImageView)findViewById(R.id.baike_jiantou_right);
        baike_image1=(ImageView)findViewById(R.id.baike_image1);
        mAdapter=new ViewpagerAdapter();
        viewpager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                baike_yema_tv.setText(position+1+"/"+viewContainter.size());

                if(position+1<viewContainter.size()){
                    baike_jiantou_left.setVisibility(View.VISIBLE);
                    baike_jiantou_right.setVisibility(View.VISIBLE);
                }
                if (position==0){
                    baike_jiantou_left.setVisibility(View.GONE);
                    baike_jiantou_right.setVisibility(View.VISIBLE);
                }
                if(position+1==viewContainter.size()){
                    baike_jiantou_left.setVisibility(View.VISIBLE);
                    baike_jiantou_right.setVisibility(View.GONE);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        if(Login2Activity.baike_token!=null) {
            RequestQueue rq = Volley.newRequestQueue(XiaobaikeActivity.this.getApplicationContext());
            JsonObjectRequest request = new JsonObjectRequest("http://121.201.14.248:8062/api/wangwangba/wiki/" + Login2Activity.baike_token, null,
                    new Response.Listener<JSONObject>() {

                        @Override
                        public void onResponse(JSONObject jsonObject) {
                            try {
                                JSONObject obj = jsonObject.getJSONObject("data");
                                JSONArray arr = obj.getJSONArray("list");
                                String IV_URL = obj.getString("image");
                                RequestQueue mQueue = Volley.newRequestQueue(XiaobaikeActivity.this);
                                ImageRequest imageRequest = new ImageRequest(
                                        IV_URL,
                                        new Response.Listener<Bitmap>() {
                                            @Override
                                            public void onResponse(Bitmap response) {
                                                baike_image1.setImageBitmap(response);
                                                map.put("image_tupian", response);
                                            }
                                        }, 0, 0, Bitmap.Config.RGB_565, new Response.ErrorListener() {
                                    @Override
                                    public void onErrorResponse(VolleyError error) {
//                                    erweima_login.setImageResource(R.drawable.default_image);
                                    }
                                });
                                mQueue.add(imageRequest);
                                for (int i = 0; i < arr.length(); i++) {
                                    JSONObject tx = arr.getJSONObject(i);
                                    View v1 = LayoutInflater.from(XiaobaikeActivity.this).inflate(R.layout.baike_textview_xml, null);
                                    TextView tv1 = (TextView) v1.findViewById(R.id.baike_tv1);
                                    tv1.setText(Html.fromHtml(tx.getString("content")));

                                    viewContainter.add(v1);
                                }
                                viewpager.setAdapter(mAdapter);
                                baike_yema_tv.setText("1/" + viewContainter.size());
                                if (viewContainter.size() == 1) {
                                    baike_jiantou_left.setVisibility(View.GONE);
                                    baike_jiantou_right.setVisibility(View.GONE);
                                } else {
                                    baike_jiantou_left.setVisibility(View.GONE);
                                    baike_jiantou_right.setVisibility(View.VISIBLE);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                }
            }

            );
            rq.add(request);
        }else{
            RequestQueue rq = Volley.newRequestQueue(XiaobaikeActivity.this.getApplicationContext());
            JsonObjectRequest request = new JsonObjectRequest("http://121.201.14.248:8062/api/wangwangba/wikis/all", null,
                    new Response.Listener<JSONObject>() {

                        @Override
                        public void onResponse(JSONObject jsonObject) {
                            try {
                                JSONObject obj2 = jsonObject.getJSONObject("data");
                                JSONObject obj1=obj2.getJSONObject("faq");
                                JSONObject obj=obj1.getJSONObject("content");
                                JSONArray arr = obj.getJSONArray("contents");
                                String IV_URL = obj.getString("image");
                                RequestQueue mQueue = Volley.newRequestQueue(XiaobaikeActivity.this);
                                ImageRequest imageRequest = new ImageRequest(
                                        IV_URL,
                                        new Response.Listener<Bitmap>() {
                                            @Override
                                            public void onResponse(Bitmap response) {
                                                baike_image1.setImageBitmap(response);
                                                map.put("image_tupian", response);
                                            }
                                        }, 0, 0, Bitmap.Config.RGB_565, new Response.ErrorListener() {
                                    @Override
                                    public void onErrorResponse(VolleyError error) {
//                                    erweima_login.setImageResource(R.drawable.default_image);
                                    }
                                });
                                mQueue.add(imageRequest);
                                for (int i = 0; i < arr.length(); i++) {
                                    JSONObject tx = arr.getJSONObject(i);
                                    View v1 = LayoutInflater.from(XiaobaikeActivity.this).inflate(R.layout.baike_textview_xml, null);
                                    TextView tv1 = (TextView) v1.findViewById(R.id.baike_tv1);
                                    tv1.setText(Html.fromHtml(tx.getString("content")));

                                    viewContainter.add(v1);
                                }
                                viewpager.setAdapter(mAdapter);
                                baike_yema_tv.setText("1/" + viewContainter.size());
                                if (viewContainter.size() == 1) {
                                    baike_jiantou_left.setVisibility(View.GONE);
                                    baike_jiantou_right.setVisibility(View.GONE);
                                } else {
                                    baike_jiantou_left.setVisibility(View.GONE);
                                    baike_jiantou_right.setVisibility(View.VISIBLE);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                }
            }

            );
            rq.add(request);
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_xiaobaike, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
    private class ViewpagerAdapter extends PagerAdapter {
        @Override
        public int getCount() {
            return viewContainter.size();
        }

        //滑动切换的时候销毁当前的组件
        @Override
        public void destroyItem(ViewGroup container, int position,
                                Object object) {
            ((ViewPager) container).removeView(viewContainter.get(position));
        }

        //每次滑动的时候生成的组件
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            ((ViewPager) container).addView(viewContainter.get(position));
            return viewContainter.get(position);
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public int getItemPosition(Object object) {
            return super.getItemPosition(object);
        }


    }

    @Override
    protected void onStop() {
        super.onStop();
        Iterator iter = map.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next(); Object key = entry.getKey();
            Object val = entry.getValue();
            Bitmap a=(Bitmap)val;
            a.recycle();
        }
        System.gc();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_MENU){
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
